/*!
 * \file	options.c
 * \brief	Options
 * \author	Alexis Lucazeau - lucaze_b@epitech.eu
 * \version	1.0
 * \date	10/23/2010 08:20:55 PM
 *
 * Option parsing
 */

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>

#include "config.h"

char *strdup(const char *s);

static struct option long_options[] =
{
    {"shell", required_argument,0, 's'},
    {"input", required_argument, 0, 'i'},
    {"output", required_argument, 0, 'o'},
    {"help", no_argument, 0, 'h'},
    {0, 0, 0, 0}
};

void        print_usage(char *bin_name)
{
    printf("IShell v1.0\n");
    printf("Usage: %s [OPTIONS]...\n\n", bin_name);

    printf("OPTIONS\n");
    printf("  --shell BIN         shell to run (absolute path)\n");
    printf("  --input INPUT       specify the input fifo file\n");
    printf("  --output OUTPUT     specify the output fifo file\n");
    printf("  --help              show this usage\n\n");
}

char        *get_default_shell(char **envp)
{
    char    *ret;

    while (envp && *envp)
    {
        if (strncmp(*envp, "SHELL", 5) == 0)
        {
            ret = strdup(*envp);
            ret = ret + 6;
            return (ret);
        }
        envp++;
    }
    return ("/bin/sh");
}

char        *get_cmd(char *path)
{
    int     start;
    int     i;

    start = 0;
    i = 0;
    while (path[i] != '\0')
    {
        if (path[i] == '/')
            start = i;
        i++;
    }
    return (strdup(path) + start + 1);
}

int         get_options(int argc, char **argv, char **envp, t_options *options)
{
    int     opt;
    int     option_index;
    int     usage;

    options->shell = NULL;
    options->input = NULL;
    options->output = NULL;
    usage = 0;
    while (42)
    {
        option_index = 0;
        opt = getopt_long(argc, argv, "hsio:", long_options, &option_index);

        if (opt == -1)
            break;

        switch (opt)
        {
            case 'h':
                usage = 1;
                break;
            case 's':
                options->shell = optarg;
                break;	
            case 'i':
                options->input = optarg;
                break;
            case 'o':
                options->output = optarg;
                break;
            default:
                usage = 1;
                break;
        }
    }
    if (usage == 1)
    {
        print_usage(argv[0]);
        return (1);
    }
    if (optind < argc)
    {
        printf(STR_TOO_MANY_ARGS);
        print_usage(argv[0]);
        return (1);
    }
    if (options->shell == NULL)
        options->shell = get_default_shell(envp);
    options->shellcmd = get_cmd(options->shell);
    if (options->input == NULL)
        options->input = strdup(INPUT_FILE);
    if (options->output == NULL)
        options->output = strdup(OUTPUT_FILE);
    return (0);
}

